from typing import List, Any
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from app import crud, models, schemas
from app.api import deps

router = APIRouter()

@router.get("/", response_model=List[schemas.Workflow])
def read_workflows(
    db: Session = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    current_user: models.User = Depends(deps.get_current_user),
) -> Any:
    """
    获取工作流列表。
    """
    workflows = crud.workflow.get_multi_by_user(
        db, user_id=current_user.id, skip=skip, limit=limit
    )
    return workflows

@router.post("/", response_model=schemas.Workflow)
def create_workflow(
    *,
    db: Session = Depends(deps.get_db),
    workflow_in: schemas.WorkflowCreate,
    current_user: models.User = Depends(deps.get_current_user),
) -> Any:
    """
    创建新工作流。
    """
    workflow = crud.workflow.create_with_user(
        db=db, obj_in=workflow_in, user_id=current_user.id
    )
    return workflow

@router.get("/{workflow_id}", response_model=schemas.Workflow)
def read_workflow(
    *,
    db: Session = Depends(deps.get_db),
    workflow_id: int,
    current_user: models.User = Depends(deps.get_current_user),
) -> Any:
    """
    根据ID获取工作流。
    """
    workflow = crud.workflow.get(db=db, id=workflow_id)
    if not workflow:
        raise HTTPException(status_code=404, detail="Workflow not found")
    if workflow.user_id != current_user.id:
        raise HTTPException(status_code=400, detail="Not enough permissions")
    return workflow

@router.put("/{workflow_id}", response_model=schemas.Workflow)
def update_workflow(
    *,
    db: Session = Depends(deps.get_db),
    workflow_id: int,
    workflow_in: schemas.WorkflowUpdate,
    current_user: models.User = Depends(deps.get_current_user),
) -> Any:
    """
    更新工作流。
    """
    workflow = crud.workflow.get(db=db, id=workflow_id)
    if not workflow:
        raise HTTPException(status_code=404, detail="Workflow not found")
    if workflow.user_id != current_user.id:
        raise HTTPException(status_code=400, detail="Not enough permissions")
    workflow = crud.workflow.update(db=db, db_obj=workflow, obj_in=workflow_in)
    return workflow

@router.delete("/{workflow_id}")
def delete_workflow(
    *,
    db: Session = Depends(deps.get_db),
    workflow_id: int,
    current_user: models.User = Depends(deps.get_current_user),
) -> Any:
    """
    删除工作流。
    """
    workflow = crud.workflow.get(db=db, id=workflow_id)
    if not workflow:
        raise HTTPException(status_code=404, detail="Workflow not found")
    if workflow.user_id != current_user.id:
        raise HTTPException(status_code=400, detail="Not enough permissions")
    workflow = crud.workflow.remove(db=db, id=workflow_id)
    return {"status": "success"} 